<?php

namespace Frieza\Modules\SearchAnalyze\Apis;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Doraemon\tools\BlockType;
use \Doraemon\tools\Curl;
use \Doraemon\service\SearchOp\Schedule as SearchOpSchedule;
use \Doraemon\service\SearchOp\Analyze as SearchOpAnalyze;

class Search extends Controller
{
    // 验证权限信息
    public function Index(Request $request)
    {
        $requestData = $request->all();

        $tokenInfos = \Doraemon\model\Token::getAllToken(12277211);
        $token = is_array($tokenInfos) && $tokenInfos ? $tokenInfos[0]["hhz_token"] : "";

        $headers = [
            'User-Agent' => "HaoHaoZhu/5.4.0 (iPhone; iOS 14.4.2; Scale/3.00)-h1861d0cfd58232aeea07819-proxyhttp-did6ce7dbeca7707f553ef74b57870578a7-HaoHaoZhu5.4.0-ovid_1000000010493741-uid12277211-piPhone13_2-nwWIFI-k3vo9",
            'Cookie' => "hhz_token=".$token,
        ];

        $yapiDomain = SearchOpSchedule::getYapiDomain();
        $url = $yapiDomain."/multicontentsearch/searchall";

        $page = $requestData["page"];
        $type = $requestData["type"];
        $abTestId = isset($requestData["ab_test_id"]) && $requestData["ab_test_id"] ? $requestData["ab_test_id"] : 0;

        $startTime = "";
        if ($abTestId > 0) {
            $testInfo = \Doraemon\model\AbTest\AbTestBasicInfo::getInfoByTestId($abTestId);
            if (is_array($testInfo) && $testInfo) {
                if (isset($testInfo["test_unique_mark"]) && $testInfo["test_unique_mark"]) {
                    $fullStartTime = $testInfo["start_time"];
                    $fullStartTimeArr = explode(" ", $fullStartTime);
                    $startTime = $fullStartTimeArr[0];
                    $startTime = str_replace("-", "", $startTime);
                }
            }
        }

        $groupName = isset($requestData["group_name"]) && $requestData["group_name"] ? intval($requestData["group_name"]) : 0;

        $keyword = isset($requestData["keyword"]) && $requestData["keyword"] ?  $requestData["keyword"] : "";
        $data = [
            "keyword" => $keyword,
            "search_request_id" => "search_analyze_test",
            "search_type" => 1,
            "ab_test_id" => $abTestId,
            "group_name" => $groupName,
        ];

        if (!empty($type)) {
            $data["type"] =  $type;
        }

        if (!empty($page)) {
            $data["page"] =  $page;
        }

        $result = Curl::Request('POST', $url, ['form_params' => $data, 'headers' => $headers]);

        if (($result['json']['code'] == 1) && is_array($result['json']['data']) && $result['json']['data']) {
            $searchResult = $result['json']['data'];

            $objIds = array();

            foreach ($searchResult["rows"] as $item) {
                $type = $item["type"];
                switch ($type) {
                    case BlockType::TYPE_ANSWER:
                    case BlockType::TYPE_PHOTO:
                        if (isset($item["photo"]["photo_info"]["id"]) && $item["photo"]["photo_info"]["id"]) {
                            array_push($objIds, $item["photo"]["photo_info"]["id"]);
                        }
                        break;
                    case BlockType::TYPE_ARTICLE:
                        if (isset($item["article"]["article_info"]["aid"]) && $item["article"]["article_info"]["aid"]) {
                            array_push($objIds, $item["article"]["article_info"]["aid"]);
                        }
                        break;
                    case BlockType::TYPE_GUIDE:
                        if (isset($item["guide"]["guide_info"]["id"]) && $item["guide"]["guide_info"]["id"]) {
                            array_push($objIds, $item["guide"]["guide_info"]["id"]);
                        }
                        break;
                    case BlockType::TYPE_BLANK:
                        if (isset($item["blank"]["blank_info"]["bid"]) && $item["blank"]["blank_info"]["bid"]) {
                            array_push($objIds, $item["blank"]["blank_info"]["bid"]);
                        }
                        break;
                }
            }

            $analyzeData = SearchOpAnalyze::getAnalyzeInfos($keyword, $objIds, $abTestId, $groupName, $startTime);

            $allAnalyzeData = $analyzeData["all_analyze_data"];
            $hashObjAnalyzeData = $analyzeData["hash_obj_analyze_data"];

            foreach ($searchResult["rows"] as &$item) {
                $type = $item["type"];
                $objId = "";

                switch ($type) {
                    case BlockType::TYPE_ANSWER:
                    case BlockType::TYPE_PHOTO:
                        if (isset($item["photo"]["photo_info"]["id"]) && $item["photo"]["photo_info"]["id"]) {
                            $objId = $item["photo"]["photo_info"]["id"];
                        }
                        break;
                    case BlockType::TYPE_ARTICLE:
                        if (isset($item["article"]["article_info"]["aid"]) && $item["article"]["article_info"]["aid"]) {
                            $objId = $item["article"]["article_info"]["aid"];
                        }
                        break;
                    case BlockType::TYPE_GUIDE:
                        if (isset($item["guide"]["guide_info"]["id"]) && $item["guide"]["guide_info"]["id"]) {
                            $objId = $item["guide"]["guide_info"]["id"];
                        }
                        break;
                    case BlockType::TYPE_BLANK:
                        if (isset($item["blank"]["blank_info"]["bid"]) && $item["blank"]["blank_info"]["bid"]) {
                            $objId = $item["blank"]["blank_info"]["bid"];
                        }
                        break;
                }

                $item["query_content_analyze"] = [];
                if ($objId && isset($hashObjAnalyzeData[$objId]) && $hashObjAnalyzeData[$objId]) {
                    $item["query_content_analyze"] = [
                        [
                            "name" => "卡片曝光数",
                            "value" => $hashObjAnalyzeData[$objId]["obj_content_exp_num"],
                        ],
                        [
                            "name" => "卡片ctr",
                            "value" => $hashObjAnalyzeData[$objId]["obj_content_ctr"],
                        ],
                        [
                            "name" => "收藏次数/点击次数",
                            "value" => $hashObjAnalyzeData[$objId]["obj_content_fav_divide_click"],
                        ]
                    ];
                }
            }

            $searchResult["query_analyze"] = [
                [
                    "name" => "搜索次数",
                    "value" => $allAnalyzeData["query_search_num"],
                ],
                [
                    "name" => "卡片ctr",
                    "value" => $allAnalyzeData["total_card_ctr"],
                ],
                [
                    "name" => "搜索转化率",
                    "value" => $allAnalyzeData["total_search_trans"],
                ],
                [
                    "name" => "收藏点击转化",
                    "value" => $allAnalyzeData["total_card_fav_divide_click"],
                ],
            ];
        }

        return response()->json([
            'code' => 1,
            'data'  => $searchResult
        ]);
    }
}